//
//  LoginController.m
//  TrainTree
//
//  Created by wanghui on 2017/9/9.
//  Copyright © 2017年 YouYeShu. All rights reserved.
//
#define kTimerCount 180
#import "LoginController.h"
#import "RootController.h"
#import "LoginRequestManager.h"
#import "CourseController.h"
@interface LoginController ()<UITextFieldDelegate>
{
    NSTimer *_timer;
    NSInteger _timerCnt;
}
/**手机号输入框*/
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
/**验证码输入框*/
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
/**获取验证码*/
@property (weak, nonatomic) IBOutlet UIButton *getCodeBtn;
/**手机号登录*/
@property (weak, nonatomic) IBOutlet UIButton *phoneBtn;
/**微信登录*/
@property (weak, nonatomic) IBOutlet UIButton *wechatBtn;
@property (weak, nonatomic) IBOutlet UIView *bgView;
/**是否*/
@property(nonatomic,assign) BOOL keyBoardIsShow;

@end

@implementation LoginController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self adjustUI];
    self.tabBarController.tabBar.hidden = YES;
        self.phoneTextField.text = [USERDEFAULT objectForKey:@"phone"];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    for (UIView *view in [self.view subviews]) {
        [view endEditing:YES];
    }
}

//移动UIView
-(void)transformView:(NSNotification *)aNSNotification
{
        //获取键盘弹出前的Rect
//    NSValue *keyBoardBeginBounds = [[aNSNotification userInfo]objectForKey:UIKeyboardFrameBeginUserInfoKey];
//    CGRect beginRect = [keyBoardBeginBounds CGRectValue];
//
//        //获取键盘弹出后的Rect
//    NSValue *keyBoardEndBounds = [[aNSNotification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey];
//    CGRect  endRect = [keyBoardEndBounds CGRectValue];

        //获取键盘位置变化前后纵坐标Y的变化值
//    CGFloat deltaY = endRect.origin.y - beginRect.origin.y;
//    NSLog(@"看看这个变化的Y值:%f",deltaY);

        //在0.25s内完成self.view的Frame的变化，等于是给self.view添加一个向上移动deltaY的动画

    if (!self.keyBoardIsShow) {
        [UIView animateWithDuration:0.25f animations:^{
            [self.view setFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - 100, self.view.frame.size.width, self.view.frame.size.height)];

        }];
    }
    self.keyBoardIsShow = YES;
}

-(void)keyboardWillHide:(NSNotification *)note
{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];

    self.keyBoardIsShow = NO;
}


- (void)adjustUI
{
    self.phoneBtn.layer.cornerRadius = 4;
    self.phoneBtn.layer.masksToBounds = YES;
    self.wechatBtn.layer.cornerRadius = 4;
    self.wechatBtn.layer.masksToBounds = YES;
    self.wechatBtn.layer.borderWidth = 1;
    self.wechatBtn.layer.borderColor = [UIColor colorWithRed:44.0f/255.0f green:126.0f/255.0f blue:194.0f/255.0f alpha:1.0].CGColor;

    if ([UIDevice is4InchiPhone]) {
        self.keyBoardIsShow = NO;
        [self.getCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            //注册观察键盘的变化
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(transformView:) name:UIKeyboardWillChangeFrameNotification object:nil];

            //注册键盘隐藏通知
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillHide:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];

    }
}
- (IBAction)dismissCurrentVc:(id)sender {
//    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)getCodeClick:(id)sender {
    WeakSelf(ws);
    [self sendVerifyCode];
    if(self.phoneTextField.text.length == 11) {
        [LoginRequestManager getCodeWithMobile:self.phoneTextField.text response:^(id JSONData, NSError *error, NSURLSessionDataTask *dataTask) {
            [SVProgressHUD showSuccessWithStatus:@"获取验证码成功"];
            if (JSONData[@"d"]) {
                ws.codeTextField.text = JSONData[@"d"];
            }

        }];

    } else {
        [SVProgressHUD showErrorWithStatus:@"格式不正确"];
        return ;
    }
    [self.view endEditing:YES];
}

#pragma mark - 获取验证码
- (void)sendVerifyCode
{
    _timerCnt = kTimerCount;
    [_getCodeBtn setEnabled : NO];
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
}

- (void)onTimer:(id)timer
{
    if (_timerCnt > 0){
        _timerCnt--;
    }

    if (_timerCnt == 0 ){
        [_timer invalidate];
        _timer = nil;
        [_getCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        _getCodeBtn.enabled = YES;

    }else{
        self.getCodeBtn.enabled = NO;
        _getCodeBtn.titleLabel.textColor = [UIColor blackColor];
        [_getCodeBtn setTitle:[NSString stringWithFormat:@"%ld",(long)_timerCnt] forState:UIControlStateNormal];
    }
}


- (IBAction)phoneLoginClick:(id)sender {
    [self.view endEditing:YES];
    if (self.phoneTextField.text.length == 11 && self.codeTextField.text.length == 4 ) {
        // 发请求登录
        [USERDEFAULT setObject:self.phoneTextField.text forKey:@"phone"];
        [LoginRequestManager loginWithMobile:self.phoneTextField.text Code:self.codeTextField.text response:^(id JSONData, NSError *error, NSURLSessionDataTask *dataTask) {
            if (JSONData) {// 登录成功
                [self dismissViewControllerAnimated:YES completion:nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccess" object:nil];
            }
        }];
    }else{
            if (self.phoneTextField.text.length != 11) {
                [SVProgressHUD showErrorWithStatus:@"手机号格式不正确"];
                return ;
            }

            if (self.codeTextField.text.length != 4 ) {
                [SVProgressHUD showErrorWithStatus:@"验证码不正确"];
                return ;
            }

        }
}

- (IBAction)wechatLoginClick:(id)sender {
    [self.view endEditing:YES];
}
 
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
